import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

function readFromStorage(key, defaultValue) {
  try { return uni.getStorageSync(key) || defaultValue } catch (e) { return defaultValue }
}

const initialToken = readFromStorage('token', '')
const initialUserId = readFromStorage('userId', null)
const initialExpireAt = readFromStorage('token_expire_at', 0)

const store = new Vuex.Store({
  state: {
    token: initialToken,
    userId: initialUserId,
    expiresAt: Number(initialExpireAt) || 0
  },
  getters: {
    isLoggedIn(state) {
      if (!state.token) return false
      if (!state.expiresAt) return true
      return Date.now() < Number(state.expiresAt)
    },
    authHeader(state) {
      if (!state.token) return ''
      return state.token.startsWith('Bearer') ? state.token : `Bearer ${state.token}`
    }
  },
  mutations: {
    setAuth(state, payload) {
      const { token, userId, expiresAt } = payload || {}
      state.token = token || ''
      state.userId = typeof userId === 'number' || typeof userId === 'string' ? userId : null
      state.expiresAt = Number(expiresAt) || 0
    },
    clearAuth(state) {
      state.token = ''
      state.userId = null
      state.expiresAt = 0
    }
  },
  actions: {
    saveAuth({ commit }, payload) {
      const token = payload && payload.token ? String(payload.token) : ''
      const userId = payload && payload.userId != null ? payload.userId : null
      const expiresIn = payload && payload.expiresIn ? Number(payload.expiresIn) : 0
      const expiresAt = expiresIn > 0 ? (Date.now() + expiresIn * 1000) : 0

      // persist
      try {
        uni.setStorageSync('token', token)
        uni.setStorageSync('Authorization', token.startsWith('Bearer') ? token : `Bearer ${token}`)
        if (userId != null) uni.setStorageSync('userId', userId)
        if (expiresAt) uni.setStorageSync('token_expire_at', expiresAt)
      } catch (e) {}

      commit('setAuth', { token, userId, expiresAt })
    },
    logout({ commit }) {
      try {
        uni.removeStorageSync('token')
        uni.removeStorageSync('Authorization')
        uni.removeStorageSync('userId')
        uni.removeStorageSync('token_expire_at')
      } catch (e) {}
      commit('clearAuth')
      try { uni.reLaunch({ url: '/fk/LoginPage/index' }) } catch (e) {}
    }
  }
})

export default store


